package org.example.maventest;

/**
 * @author hqz
 * @version 1.0.0
 * @ClassName App
 * @Description TODO
 * @createTime 2021年12月04日 09:32:00
 */

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import org.example.maventest.utils.AuthorizationUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

public class App extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {

        Pane root = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("/fxml/stage.fxml")));
        primaryStage.setScene(new Scene(root, 640, 360));
        primaryStage.getIcons().add(new Image("images/lol.png"));
        primaryStage.setTitle("lolHelper");
        primaryStage.show();

        // 自从那天起，我就独自照看着历代的星辰。

        // 关闭默认的退出事件
        Platform.setImplicitExit(false);
        primaryStage.setOnCloseRequest(event -> {
            event.consume();
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("退出程序");
            alert.setHeaderText(null);
            alert.setContentText("您是否要退出程序？");
            Optional<ButtonType> result = alert.showAndWait();
            if(result.get() == ButtonType.OK){
                Platform.exit();
            }
        });
    }

    @Override
    public void init() throws Exception {
        File file = new File("E:\\desktop\\lol.txt");
        // 文件不存在，直接返回
        if(!FileUtil.exist(file)){
            return;
        }
        List<String> stringList = FileUtil.readLines(file, "UTF-8");
        if(stringList.size()>=1){
           AuthorizationUtil.port =  stringList.get(0).split("=")[1];
           AuthorizationUtil.password =  stringList.get(1).split("=")[1];
        }
        super.init();
    }

    public JSONObject accessLolApiByGet(String url){
        String body = HttpRequest.get(AuthorizationUtil.buildUrl(url))
                .header("Authorization",AuthorizationUtil.getAuthorization())
                .execute()
                .body();
        if(StrUtil.isNotBlank(body)){
           return JSONUtil.parseObj(body);
        }
        return new JSONObject();
    }

    public JSONObject accessLolApiByPost(String url){
        String body = HttpRequest.post(AuthorizationUtil.buildUrl(url))
                .header("Authorization",AuthorizationUtil.getAuthorization())
                .execute()
                .body();
        if(StrUtil.isNotBlank(body)){
            return JSONUtil.parseObj(body);
        }
        return new JSONObject();
    }

    /**
     *
     * @return
     * @throws
     */
    private String executeTask(String cmd){
        Process process = null;
        try {
            ProcessBuilder pb = new ProcessBuilder();
            pb.command(cmd);
            process = pb.start();

            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")));

            BufferedReader stdError = new BufferedReader(new
                    InputStreamReader(process.getErrorStream(), Charset.forName("GBK")));

            StringBuilder stringBuilder = new StringBuilder();
            String r = "";
            while ((r = br.readLine()) != null) {
                stringBuilder.append(r);
            }
            // 等待 process 执行完毕
            process.waitFor();
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (process != null){
                process.destroy();
            }
        }
        return "";
    }
}
